//
//  LQMediator.m
//  LQBaseKit
//
//  Created by 戴志朋 on 16/4/11.
//  Copyright © 2016年 hzdracom. All rights reserved.
//

#import "LQMediator.h"

@implementation LQMediator

+ (instancetype)sharedInstance
{
    static LQMediator *mediator;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        mediator = [[LQMediator alloc] init];
    });
    return mediator;
}

- (id)performActionWithUrl:(NSURL *)url
                completion:(void (^)(NSDictionary *))completion {
    NSDictionary *infoDic = [[NSBundle mainBundle] infoDictionary];
    NSDictionary *firstSchemeDic = [[infoDic objectForKey:@"CFBundleURLTypes"] firstObject];
    NSString *appScheme = [[firstSchemeDic objectForKey:@"CFBundleURLSchemes"] firstObject];
    if (![url.scheme isEqualToString:appScheme]) {
        //处理404
        return @(NO);
    }
    
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    NSString *urlString = [url query];
    for (NSString *param in [urlString componentsSeparatedByString:@"&"]) {
        NSArray *elts = [param componentsSeparatedByString:@"="];
        if([elts count] < 2) continue;
        [params setObject:[elts lastObject] forKey:[elts firstObject]];
    }
    
    //出于安全考虑，防止黑客通过远程方式调用本地模块。
    NSString *actionName = [url.path stringByReplacingOccurrencesOfString:@"/" withString:@""];
    if ([actionName hasPrefix:@"native"]) {
        return @(NO);
    }
    
    id result = [self performTarget:url.host action:actionName params:params resultAction:nil];
    if (completion) {
        if (result) {
            completion(@{@"result":result});
        } else {
            completion(nil);
        }
    }
    return result;
}

- (id)performTarget:(NSString *)targetName
             action:(NSString *)actionName
             params:(NSDictionary *)params
       resultAction:(void(^)(NSDictionary *info))resultAction {
    
    NSString *targetClassString = [NSString stringWithFormat:@"Target%@", targetName];
    NSString *actionString = [NSString stringWithFormat:@"action%@:", actionName];
    
    Class targetClass = NSClassFromString(targetClassString);
    id target = [[targetClass alloc] init];
    SEL action = NSSelectorFromString(actionString);
    
    if (target == nil) {
        //可以固定的target顶上。
        return nil;
    }
    
    if ([target respondsToSelector:action]) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
        return [target performSelector:action withObject:params];
#pragma clang diagnostic pop
    } else {
        // 这里是处理无响应请求的地方，如果无响应，则尝试调用对应target的notFound方法统一处理
        SEL action = NSSelectorFromString(@"notFound:");
        if ([target respondsToSelector:action]) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
            return [target performSelector:action withObject:params];
#pragma clang diagnostic pop
        } else {
            // 这里也是处理无响应请求的地方，在notFound都没有的时候，可以用前面提到的固定的target顶上。
            return nil;
        }
    }
}

@end
